<?php
namespace app\oem\controller;
use think\Controller;
use think\Db;
use app\common\controller\OemBaseController;
use app\common\model\Csv;

class Accounts extends OemBaseController
{
 	protected $csv;
    protected function _initialize() {
        parent::_initialize();
        $this->csv = new Csv();
    }
    
	//帐号管理
	public function user()
    {
    	$user_level=session("user_level");
		if($user_level==1){//oem
			$where['a.oem_id']=session('d_id');
		}elseif($user_level==2){//省代理
			$where['a.agency_id1']=session('d_id');
		}elseif($user_level==3){
			$where['a.agency_id2']=session('d_id');
		}
		if(input("mobile")){
			$where['a.mobile']=["like","%".input("mobile")."%"];
			$this->assign("mobile",input("mobile"));
		}else{ 
			$this->assign("mobile",'');
		}
		
		if(input("user_no")){
			$where['a.id']=["like","%".input("user_no")."%"];
			$this->assign("user_no",input("user_no"));
		}else{ 
			$this->assign("user_no",'');
		}
		
		$fx_total=db("info_user")->where("is_fx=1")->count();
		$this->assign("fxs",$fx_total);
		$level = db('info_user')->field('count(id) as count,level')->group('level')->buildSql();
		$cz = db('log_paylog_copy')->field('sum(balance) as cz,uid')->where("order_type=8")->group('uid')->buildSql();
		
    	$list=db('info_user')->alias('a')		
		->join($level.'b','b.level = a.id','LEFT')
		->join('info_oem c','a.agency_id2 = c.id','LEFT')
		->join("info_agent d","a.tj_agent=d.id",'LEFT')
		->join("info_user e","a.level=e.id",'LEFT')
		->join($cz."f","f.uid=a.id",'LEFT')
		->field('f.cz,a.id,a.user_name,a.mobile,a.balance,a.commission,a.score,a.status,a.add_time,b.count,c.user_name as city_name,d.agent_name,e.mobile as tmobile')
		->where($where)->order('a.add_time desc')->paginate(15);
		$this->assign("list",$list);
		$this->assign('empty','<span class="empty">没有数据</span>');
    	return $this->fetch();
    }
    //会员改变状态
	public function user_status()
    {
    	$where['status'] = input('status');
    	$ress = db('info_user')->where('id',input('id'))->update($where);
    	if($ress){
			return json(['code'=>200,'msg'=>'成功']);
		}else{
			return json(['code'=>402,'msg'=>'失败']);
		}
    }
    public function agent()
    {
    	$user_level=session("user_level");
		if($user_level==1){//oem
			$where['a.oem_id']=session('d_id');
		}elseif($user_level==2){//省代理
			$where['a.agency_id1']=session('d_id');
		}elseif($user_level==3){
			$where['a.agency_id2']=session('d_id');
		}
		if(input('agent_name')){
			$query['agent_name'] = input('agent_name');
			$this->assign("agent_name",input("agent_name"));
			$where['a.agent_name'] = ['like', '%'.input('agent_name').'%'];
		}else{
			$this->assign("agent_name",'');
		}
		if(input('mobile')){
			$query['mobile'] = input('mobile');
			$this->assign("mobile",input("mobile"));
			$where['a.mobile'] = input('mobile');
		}else{
			$this->assign("mobile",'');
		}
		
		if(input('ch_city')){
			$query['a.agency_id2'] = input('mobile');
			$where['a.agency_id2'] = input('ch_city');
		}
		
		//推广
		$tjagent = db('info_user')->field('count(id) as count,tj_agent')->group('tj_agent')->buildSql();
		//合伙人
		$puuser = db('info_user')->field('count(id) as counts,tj_agent')->where('is_pt',1)->group('tj_agent')->buildSql();
		
    	$list=db('info_agent')->alias('a')		
		->join($tjagent.'b','b.tj_agent = a.id','LEFT')
		->join($puuser.'c','c.tj_agent = a.id','LEFT')
		->join('info_oem d','a.agency_id2 = d.id','LEFT')
		->where($where)->order('a.add_time desc')
		->field('a.id,a.agent_name,a.mobile,a.balance,a.score,a.store_property,a.is_huilu,a.address,a.is_state,a.status,a.add_time,b.count,c.counts,d.user_name as city_name')
		->paginate(15,false,['query'=>request()->param()]);
		$this->assign("list",$list);
		$this->assign('empty','<span class="empty">没有数据</span>');
		
		if(session('d_id')==1){
			$wheres['oem_id'] = session('d_id');
		}else{
			$wheres['agency_id'] = session('d_id');
		}
		
		$wheres['user_level'] = 3;
		//获取服务商列表
		$city = db('info_oem')->field('id,user_name')->where($wheres)->select();
		$this->assign('city',$city);
    	return $this->fetch();
    }
	//商家改变状态
	public function agent_status()
    {
    	$where['status'] = input('status');
    	$ress = db('info_agent')->where('id',input('id'))->update($where);
    	if($ress){
			return json(['code'=>200,'msg'=>'成功']);
		}else{
			return json(['code'=>402,'msg'=>'失败']);
		}
    }
    
    //修改商家显示状态
    function agent_display(){
    	$where['is_huilu'] = input('status');
    	$ress = db('info_agent')->where('id',input('id'))->update($where);
    	if($ress){
			return json(['code'=>200,'msg'=>'成功']);
		}else{
			return json(['code'=>402,'msg'=>'失败']);
		}
    }
	
	public function show_agent(){
		$account=db('info_agent')->find(input("id"));
		$this->assign('ad',$account);
		return $this->fetch();
	}
	//修改商家费率
	public function upagent_huilv()
    {
    	if(request()->isPost()){
	    	$where['temp_fee'] = input('cb_huilu');
			$where['is_huilu'] = 2;
	    	$ress = db('info_agent')->where('id',input('id'))->update($where);
	    	if($ress){
				return json(['code'=>200,'msg'=>'提交成功等待通过']);
			}else{
				return json(['code'=>402,'msg'=>'提交失败']);
			}
    	}
    	$this->assign("id",input('id'));
    	return $this->fetch();
    }
    public function agency_id1()
    {
    	$user_level=session("user_level");
		if($user_level==1){//oem
			$where['a.oem_id']=session('d_id');
		}		
		//查询省代下市代数量
		$map['user_level'] = 3;
		$map['user_type'] = 1;
		$map['oem_id'] = session('d_id');
		$city = db('info_oem')->field('count(id) as count,agency_id')->where($map)->group('agency_id')->buildSql();
		
		$where['user_level']=2;
    	$list=db('info_oem')->alias('a')		
		->join($city.'b','b.agency_id = a.id','LEFT')
		->field('a.id,a.user_name,a.province,a.mobile,a.balance,a.commission,a.score,a.is_verify,a.status,a.add_time,b.count')
    	->where($where)
		->order('a.add_time desc')
    	->select();
		$this->assign("list",$list);
		$this->assign('empty','<span class="empty">没有数据</span>');
    	return $this->fetch();
    }
    public function agency_id2()
    {
		$user_level=session("user_level");
		if($user_level==1){//oem
			$where['a.oem_id']=session('d_id');
		}elseif($user_level==2){//oem
			$where['a.agency_id']=session('d_id');
		}

		//推广的商家数
		$agentcount = db('info_agent')->field('count(id) as count,agency_id2')->where('agency_id2','<>',0)->group('agency_id2')->buildSql();				
		
		$where['a.user_level']=3;
		$field = 'a.*,t.user_name as tname,b.count';
    	$list = Db::name("info_oem")->alias('a')
    	->join($agentcount.'b','b.agency_id2 = a.id','LEFT')
		->join('info_oem t','t.id = a.agency_id','LEFT')->
		field($field)->where($where)->order('a.add_time desc')->paginate(10);
    	
		$this->assign("list",$list);
		$this->assign('empty','<span class="empty">没有数据</span>');
    	return $this->fetch();
    }
    //业务员
    public function salesman()
    {
    	$user_level=session("user_level");
		if($user_level==1){//oem
			$where['oem_id']=session('d_id');
		}elseif($user_level==2){//省代理
			$where['agency_id1']=session('d_id');
		}elseif($user_level==3){
			$where['agency_id2']=session('d_id');
		}
    	$list=db('info_salesman')->where($where)->select();
		$this->assign("list",$list);
		$this->assign('empty','<span class="empty">没有数据</span>');
    	return $this->fetch();
    }
	//添加商家
	public function add_agent(){
		if(request()->isPost()){
			$is_reg=db('info_agent')->where("mobile",input("mobile"))->find();
			if($is_reg){
				return json(['code'=>402,'msg'=>'添加失败,该手机号码已经添加过']);
			}
			$cut_infor_oem = db('info_oem')->where("id",session('d_id'))->find();
			
			$is_userreg=db('info_user')->where("mobile",input("mobile"))->find();
			if($is_userreg){
				//已经存在会员信息
				$user_id= $is_userreg['id'];
				$where['oem_id'] 	 = $cut_infor_oem['oem_id'];
				$where['agency_id1'] = $cut_infor_oem['agency_id'];
				$where['agency_id2'] = $cut_infor_oem['id'];
	    		$ress = db('info_user')->where('id',$is_userreg['id'])->update($where);
			}else{
				//同时添加会员
				$datas['mobile'] 	 = input("mobile");
				$datas['password'] 	 = md5_salt("123456");
				$datas['oem_id'] 	 = $cut_infor_oem['oem_id'];
				$datas['agency_id1'] = $cut_infor_oem['agency_id'];
				$datas['agency_id2'] = $cut_infor_oem['id'];
				$datas['add_time']	 =now_time();
				db('info_user')->insert($datas);
				$user_id= Db::name('info_user')->getLastInsID();
			}
									
			$param['user_id'] 	= $user_id;
			$param['add_time'] 	= now_time();
			$param['mobile'] 	= input("mobile");
			$param['agent_name'] 	= input("agent_name");
			$param['user_name'] 	= input("user_name");
			$param['logo']	=input("thumb");
			$param['store_property'] 	= input("store_property");
			$param['password'] 	= md5_salt("123456");
			$param['operation_pwd'] 	= md5_salt("123456");
			$user_level=session("user_level");
			$param['oem_id']	=$cut_infor_oem['oem_id'];
			$param['agency_id1']=$cut_infor_oem['agency_id'];
			$param['agency_id2']=$cut_infor_oem['id'];
			$res = db('info_agent')->insert($param);
			if($res){
				$agent_id= Db::name('info_agent')->getLastInsID();
				$data['agent_id']=$agent_id;
				$data['oem_id']=session('oem_id');
				$data['store_name']=input("agent_name");
				$data['add_time']=now_time();
				db('agent_store')->insert($data);				
				return json(['code'=>200,'msg'=>'添加成功','data'=>$param]);
			}else{
				return json(['code'=>402,'msg'=>'添加失败']);
			}
    	}
    	return $this->fetch();
	}
	//添加省代
    public function add_agency(){
    	if(request()->isPost()){
			$is_reg=db('info_oem')->where("mobile",input("mobile"))->find();
			if($is_reg){
				return json(['code'=>402,'msg'=>'添加失败,该手机号码已经添加过']);
			}
			$param['add_time'] 		= now_time();
			$param['mobile'] 		= input("mobile");
			$param['province'] 		= input("province");
			$param['user_name'] 	= input("user_name");
			$param['password'] 		= md5_salt(input("password"));
			$param['operation_pwd'] = md5_salt(input("operation_pwd"));
			$param['status'] 		= input("status");
			$param['user_level']  	= 2;
			$param['oem_id']=session('d_id');
		
			$res = db('info_oem')->insert($param);
			if($res){
				return json(['code'=>200,'msg'=>'添加成功','data'=>$param]);
			}else{
				return json(['code'=>402,'msg'=>'添加失败']);
			}
			
    	}
    	return $this->fetch();
    }
    //添加业务员
    public function add_manager(){
    	if(request()->isPost()){
			$is_reg=db('info_salesman')->where("mobile",input("mobile"))->find();
			if($is_reg){
				return json(['code'=>402,'msg'=>'添加失败,该手机号码已经添加过']);
			}
			
			$cut_infor_oem = db('info_oem')->where("id",session('d_id'))->find();
			$param['add_time'] 		= now_time();
			$param['mobile'] 		= input("mobile");
			$param['name'] 			= input("name");
			$param['oem_id']		= $cut_infor_oem['oem_id'];
			$param['agency_id1']	= $cut_infor_oem['agency_id'];
			$param['agency_id2']	= $cut_infor_oem['id'];
			$res = db('info_salesman')->insert($param);
			if($res){
				return json(['code'=>200,'msg'=>'添加成功','data'=>$param]);
			}else{
				return json(['code'=>402,'msg'=>'添加失败']);
			}
			
    	}
    	return $this->fetch();
    }
    public function edit_agency(){
		if(request()->isPost()){
			$param['update_time'] = now_time();
			$param['mobile'] 	= input("mobile");
			$param['user_name'] 	= input("user_name");
			if(input("password")){
				$param['password'] 	= md5_salt(input("password"));
			}
			if(input("operation_pwd")){
				$param['operation_pwd'] = md5_salt(input("operation_pwd"));
			}
			$param['status'] = input("status");
			$param['id'] = input("id");
			$res = db('info_oem')->update($param);
			if($res){
				return json(['code'=>200,'msg'=>'修改成功','data'=>$param]);
			}else{
				return json(['code'=>402,'msg'=>'修改失败']);
			}
    	}
		$account=db('info_oem')->find(input("id"));
		$this->assign('ad',$account);
		return $this->fetch();
	}
	//添加市代
	public function add_agency2(){
		if(request()->isPost()){
			$is_reg=db('info_oem')->where("mobile",input("mobile"))->find();
			if($is_reg){
				return json(['code'=>402,'msg'=>'添加失败,该手机号码已存在']);
			}
			
			$cut_infor_oem = db('info_oem')->where("id",session('d_id'))->find();
			$param['add_time'] 		= now_time();
			$param['mobile'] 		= input("mobile");
			$param['province'] 		= input("province");
			$param['city'] 			= input("city");
			$param['user_name'] 	= input("user_name");
			$param['addres'] 		= input("addres");
			$param['password'] 		= md5_salt(input("password"));
			$param['status'] 		= input("status");
			$param['user_level']  	= 3;
			$param['oem_id']		= $cut_infor_oem['id'];
			$param['agency_id']		= input("ch_province");
		
			$res = db('info_oem')->insert($param);
			$city_id= Db::name('info_oem')->getLastInsID();
			if($res){
				$is_userreg=db('info_user')->where("mobile",input("mobile"))->find();
				if($is_userreg){
					$datas['agency_id1'] = input("ch_province");
					$datas['agency_id2'] = $city_id;
					$datas['is_city'] 	 = $city_id;
					$datas['is_fx'] 	 = 1;
					$datas['level'] 	 = $is_userreg['id'];
					if($is_userreg['is_agent']==2){
						$agent_info = db('info_agent')->where("user_id",$is_userreg['id'])->find();
						$datas['tj_agent'] 	= $agent_info['id'];
					}
					$user = db('info_user')->where('id',$is_userreg['id'])->update($datas);
				}else{
					//同时添加会员
					$datas['mobile'] 	 = input("mobile");
					$datas['password'] 	 = md5_salt("123456");
					$datas['oem_id'] 	 = session('d_id');
					$datas['agency_id1'] = input("ch_province");
					$datas['agency_id2'] = $city_id;
					$datas['is_city'] 	 = $city_id;
					$datas['is_fx'] 	 = 1;
					$datas['level'] 	 = 1;
					$datas['add_time']	 = now_time();
					$user = db('info_user')->insert($datas);			
				}
				if($user){
					return json(['code'=>200,'msg'=>'添加成功','data'=>$param]);
				}		
			}else{
				return json(['code'=>402,'msg'=>'添加失败']);
			}
			
    	}
		
		//获取省代列表
		$province = db('info_oem')->field('id,user_name')->where('user_level',2)->where('oem_id',session('d_id'))->select();
		$this->assign('province',$province);
    	return $this->fetch();
	}
	
	//联盟商圈审核
	public function union_sh(){
		
		if(request()->isPost()){
    		$param=input('post.');
			if(!empty($param['store_name']))$where['a.name'] = ['like','%'.$param['store_name'].'%'];
			if(!empty($param['state']))$where['a.state'] = $param['state'];
    	}
    	$where['a.oem_id'] = session('d_id');
    	$list = Db::table('union_agent')
    	->alias('a')
		->field('a.id,a.sq_name,a.address,a.name,a.tel,a.state,a.is_state,b.user_name')
    	->join('info_user b','a.u_id = b.id')
    	->where($where)
    	->order('a.add_time desc')
    	->paginate(20);
        $this->assign('list',$list);
        $this->assign('empty','<span class="empty">没有数据</span>');
    	return $this->fetch();
	}
	
	//联盟商圈审核
	public function union_shenhe(){
    	$param['state'] = input("lid");
    	$list = Db::table('union_agent')->where('id',input("id"))->update($param);
    	if($list){
			return json(['code'=>200,'msg'=>'成功']);
		}else{
			return json(['code'=>402,'msg'=>'失败']);
		}
	}
	//业务员推广二维码
	public function tuiguang(){
    	$data = Db::table('info_salesman')->where('id',input("id"))->find();
		//二维码链接
    	$redirect_url="http://".$_SERVER['HTTP_HOST']."/index/index/regist?fromuid=1".
    	"&oem_id=".$data['oem_id']."&salesman_id=".$data['id'];
		$data['redirect_url'] = $redirect_url;
    	
    	$this->assign('data',$data);
    	return $this->fetch();
	}
	
	
    //商家导出
    public function agent_dcxml(){
	 	$param = input('post.');
		$query=[];
		//商家
		if(input('agent_name')){
			$query['a.agent_name'] = input('agent_name');
			$this->assign("agent_name",input("agent_name"));
			$where['a.agent_name'] = ['like', '%'.input('agent_name').'%'];
		}else{
			$this->assign("agent_name",'');
		}
		if(input('mobile')){
			$query['a.mobile'] = input('mobile');
			$this->assign("mobile",input("mobile"));
			$where['a.mobile'] = input('mobile');
		}else{ 
			$this->assign("mobile",'');
		}
		if(session('user_level')==1){
			$where['a.oem_id'] = session('d_id');
		}elseif(session('user_level')==2){
			$where['a.agency_id1'] = session('d_id');
		}else{
			$where['a.agency_id2'] = session('d_id');
		}
		
		//推广
		$tjagent = db('info_user')->field('count(id) as count,tj_agent')->group('tj_agent')->buildSql();
		//合伙人
		$puuser = db('info_user')->field('count(id) as counts,tj_agent')->where('is_pt',1)->group('tj_agent')->buildSql();
		
    	$list=db('info_agent')->alias('a')		
		->join($tjagent.'b','b.tj_agent = a.id','LEFT')
		->join($puuser.'c','c.tj_agent = a.id','LEFT')
		->join('info_oem d','a.agency_id2 = d.id','LEFT')
		->where($where)->order('a.add_time desc')
		->field('a.id,a.agent_name,a.mobile,a.balance,a.score,a.store_property,a.address,a.is_state,a.status,a.add_time,b.count,c.counts,d.user_name as city_name')
		->select();
		$str ="店铺名称,服务商,手机号码,余额,鼓励金,店铺性质,地址,资质认证,推广数,创业股东,状态,创建时间,"."\n";
        $str = iconv('utf-8','gbk',$str);
        foreach($list as $k=>$row){
        	$agent_name = iconv('utf-8','gbk',$row['agent_name']);
			$city_name = iconv('utf-8','gbk',$row['city_name']);
			$tel = iconv('utf-8','gbk','	'.$row['mobile']);
			//$sex = iconv('utf-8','gbk',$row['sex']);
			//$nick_name = utf8ToGbk($row['nick_name']);
			$balance = iconv('utf-8','gbk','	'.$row['balance']);
			$score = iconv('utf-8','gbk','	'.$row['score']);
			if($row['store_property']==1){
				$property = '个人';
			}elseif($row['store_property']==2) {
				$property = '企业';
			}else{
				$property = '个体户';
			}
			$propertyname = iconv('utf-8','gbk',$property); 
			$address = iconv('utf-8','gbk',$row['address']);
			if($row['is_state']==1){
				$state = '已签约';
			}else{
				$state = '未签约';
			}
			$statename = iconv('utf-8','gbk',$state);
			$count = iconv('utf-8','gbk',$row['count'] ? $row['count']:0);
			$counts = iconv('utf-8','gbk',$row['counts'] ? $row['counts']:0);
			if($row['status']==1){
				$status = '正常';
			}else{
				$status = '冻结';
			}
			$statusname = iconv('utf-8','gbk',$status);
			$add_time = iconv('utf-8','gbk','	'.$row['add_time']);
			$str .= $agent_name.",".$city_name.",".$tel.",".$balance.",".$score.",".$propertyname.",".$address.",".$statename.",".$count.",".$counts.",".$statusname.",".$add_time.","."\n"; //用引文逗号分开 
        } 

	  	$filename ='商家列表.csv';   //设置文件名  
    	
        header("Content-type:text/csv"); 
        header("Content-Disposition:attachment;filename=".$filename); 
        header('Cache-Control:must-revalidate,post-check=0,pre-check=0'); 
        header('Expires:0'); 
        header('Pragma:public'); 
        echo $str; 
        exit;
	}
	//会员导出
    public function user_dcxml(){
	 	$param = input('post.');
		$query=[];
		if(input('mobile')){
			$query['mobile'] = input('mobile');
			$this->assign("mobile",input("mobile"));
			$where['a.mobile'] = input('mobile');
		}else{
			$this->assign("mobile",'');
		}
		if(session('user_level')==1){
			$where['a.oem_id'] = session('d_id');
		}elseif(session('user_level')==2){
			$where['a.agency_id1'] = session('d_id');
		}else{
			$where['a.agency_id2'] = session('d_id');
		}
		
		$level = db('info_user')->field('count(id) as count,level')->group('level')->buildSql();
		
    	$list=db('info_user')->alias('a')		
		->join($level.'b','b.level = a.id','LEFT')
		->join('info_oem c','a.agency_id2 = c.id','LEFT')
		->join("info_agent d","a.tj_agent=d.id",'LEFT')
		->join("info_user e","a.level=e.id",'LEFT')
		->field('a.id,a.user_name,a.mobile,a.balance,a.commission,a.score,a.status,a.add_time,b.count,c.user_name as city_name,d.agent_name,e.mobile as tmobile')
		->where($where)->order('a.add_time desc')->select();
		$str ="手机号,会员名,服务商,商家,推荐人,余额,佣金,鼓励金,推广数,状态,注册时间,"."\n";
        $str = iconv('utf-8','gbk',$str);
        foreach($list as $k=>$row){
        	$id = iconv('utf-8','gbk',$row['id']);
			$mobile = iconv('utf-8','gbk','	'.$row['mobile']);
			$city_name = iconv('utf-8','gbk','	'.$row['city_name']);
			$agent_name = iconv('utf-8','gbk','	'.$row['agent_name']);
			$tmobile = iconv('utf-8','gbk','	'.$row['tmobile']);
			$user_name = iconv('utf-8','gbk',$row['mobile']?$row['user_name'] : '扫码会员');
			$balance = iconv('utf-8','gbk',$row['balance']);
			$commission = iconv('utf-8','gbk',$row['commission']);
			$score = iconv('utf-8','gbk',$row['score']);
			$count = iconv('utf-8','gbk',$row['count']?$row['count'] : 0);
			if($row['status']==1){
				$payname = '正常';
			}else {
				$payname = '冻结 ';
			}
			$typename = iconv('utf-8','gbk',$payname); 
			$add_time = iconv('utf-8','gbk','	'.$row['add_time']);
			$str .= $mobile.",".$user_name.",".$city_name.",".$agent_name.",".$tmobile.",".$balance.",".$commission.",".$score.",".$count.",".$typename.",".$add_time.","."\n"; //用引文逗号分开 
        } 

	  	$filename ='会员列表.csv';   //设置文件名  
    	
        header("Content-type:text/csv"); 
        header("Content-Disposition:attachment;filename=".$filename); 
        header('Cache-Control:must-revalidate,post-check=0,pre-check=0'); 
        header('Expires:0'); 
        header('Pragma:public'); 
        echo $str; 
        exit;
	}
	
    public function show_user(){
		$account=db('info_user')->find(input("id"));
		$this->assign('ad',$account);
		return $this->fetch();
	}
    
}
